import { ref, onMounted, computed } from 'vue'

export function useNavBar() {
    const statusBarHeight = ref(20)   // 状态栏高度
    const navBarHeight = ref(64)      // 导航栏总高度（状态栏 + 导航高度）
    const menuButtonInfo = ref<any>(null) // 小程序胶囊按钮信息
    const capsuleBottomHeight = ref(0) // 胶囊底部高度

    // 计算胶囊底部高度
    const capsuleBottom = computed(() => {
        if (!menuButtonInfo.value) return 0
        return menuButtonInfo.value.top + menuButtonInfo.value.height
    })

    onMounted(() => {
        try {
            const systemInfo = uni.getSystemInfoSync()
            statusBarHeight.value = systemInfo.statusBarHeight || 20

            // #ifdef MP-WEIXIN
            // 微信小程序，使用胶囊按钮来精确计算
            const menuButton = uni.getMenuButtonBoundingClientRect()
            if (menuButton && menuButton.top) {
                menuButtonInfo.value = menuButton
                navBarHeight.value =
                    (menuButton.top - statusBarHeight.value) * 2 + menuButton.height + statusBarHeight.value
                // 计算胶囊底部高度
                capsuleBottomHeight.value = menuButton.top + menuButton.height
            } else {
                // 如果胶囊按钮信息获取失败，使用默认值
                navBarHeight.value = statusBarHeight.value + 44
                capsuleBottomHeight.value = statusBarHeight.value + 44
            }
            // #endif

            // #ifndef MP-WEIXIN
            // 其他端，默认 44px 导航栏高度
            navBarHeight.value = statusBarHeight.value + 44
            capsuleBottomHeight.value = statusBarHeight.value + 44
            // #endif
        } catch (error) {
            console.error('获取系统信息失败:', error)
            // 使用默认值
            statusBarHeight.value = 20
            navBarHeight.value = 64
            capsuleBottomHeight.value = 64
        }
    })

    return {
        statusBarHeight,
        navBarHeight,
        menuButtonInfo,
        capsuleBottomHeight,
        capsuleBottom
    }
}
